<template>
  <div id="app">
    <el-card shadow="always">
      <el-form :inline="true" size="medium" :model="BorrowSearch" class="demo-form-inline">
        <el-form-item >
          <el-input v-model="BorrowSearch.rname" placeholder="借阅人姓名" clearable></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="BorrowSearch.stime" placeholder="借阅时间" clearable></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="BorrowSearch.isbn" placeholder="借阅书籍编号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" icon="el-icon-user">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="addBookborrow" icon="el-icon-plus">添加借阅记录</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="DeleteBookborrow">批量还书</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="jump">跳转到用户信息管理</el-button>
        </el-form-item>
      </el-form>

      <el-table
          :data="BookborrowList"
          style="width: 100%"
          @selection-change="SelectionBookborrow">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="借阅编号"
            prop="id"
            align="center"
            width="180">
        </el-table-column>
        <el-table-column
            label="借阅人姓名"
            align="center"
            prop="rname">
        </el-table-column>
        <el-table-column
            label="性别"
            align="center"
            prop="sex">
        </el-table-column>
        <el-table-column
            label="电话"
            align="center"
            prop="phone">
        </el-table-column>
        <el-table-column
            label="借阅时间"
            align="center"
            prop="stime">
        </el-table-column>
        <el-table-column
            label="借阅书名"
            align="center"
            prop="bname">
        </el-table-column>
        <el-table-column
            label="借阅天数"
            align="center"
            prop="brotime">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="editBookborrow(scope.row)">编辑</el-button>
            <el-button
                size="mini"
                type="danger"
                @click="DeleteBookborrow(scope.$index,scope.row)">还书</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[2, 4, 6, 8]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>

    </el-card>

    <el-card>
      <el-form :inline="true" size="medium" :model="BookInfo" class="demo-form-inline">
        <el-form-item >
          <el-input v-model="BookInfo.bname" placeholder="书籍名" clearable></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="BookInfo.publisher" placeholder="书籍出版社" clearable></el-input>
        </el-form-item>
        <el-form-item >
          <el-select v-model="BookInfo.status" placeholder="书籍状态">
            <el-option label="所有状态" value=""></el-option>
            <el-option label="在库" value="在库"></el-option>
            <el-option label="借出" value="借出"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search2" icon="el-icon-user">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="DeleteBookInfo">批量删除</el-button>
        </el-form-item>
      </el-form>
      <el-table
          :data="bookList"
          style="width: 100%"
          @selection-change="SelectionBookInfo">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="书籍编号"
            prop="isbn"
            align="center"
            width="180">
        </el-table-column>
        <el-table-column
            label="书籍名称"
            align="center"
            prop="bname">
        </el-table-column>
        <el-table-column
            label="出版社"
            align="center"
            prop="publisher">
        </el-table-column>
        <el-table-column
            label="作者"
            align="center"
            prop="author">
        </el-table-column>
        <el-table-column
            label="借阅状态"
            align="center"
            prop="status">
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="danger"
                @click="DeleteBookInfo(scope.$index,scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          @size-change="handleSizeChange2"
          @current-change="handleCurrentChange2"
          :current-page="page2"
          :page-sizes="[2, 4, 6, 8]"
          :page-size="pageSize2"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total2">
      </el-pagination>
    </el-card>

    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
      <el-form :model="Bookbrrowedit" :rules="editStuRules" ref="ruleForm">
        <el-form-item label="借阅人编号" prop="rid" :label-width="formLabelWidth" >
          <el-input v-model.number="Bookbrrowedit.rid" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="借阅人姓名" prop="rname" :label-width="formLabelWidth" >
          <el-input v-model="Bookbrrowedit.rname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="借阅人性别" prop="sex" :label-width="formLabelWidth" >
          <el-radio v-model="Bookbrrowedit.sex" label="男">男</el-radio>
          <el-radio v-model="Bookbrrowedit.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="借阅人电话号码" prop="phone" :label-width="formLabelWidth" >
          <el-input v-model="Bookbrrowedit.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍编号" prop="isbn" :label-width="formLabelWidth" >
          <el-input v-model.number="Bookbrrowedit.isbn" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="借阅时间" prop="stime" :label-width="formLabelWidth" >
          <el-input v-model="Bookbrrowedit.stime" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="借阅天数" prop="brotime" :label-width="formLabelWidth"  >
          <el-input v-model.number="Bookbrrowedit.brotime" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveBookborrow()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import bookborrrowAPI from "@/api/bookborrow"
import bookinfoAPI from "@/api/bookinfo"

export default {
  data() {
    let checkRID = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('借阅人id不能为空'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('借阅人id必须为数字值'))
      }else {
        callback()
      }
    }

    let checkISBN = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('书籍id不能为空'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('书籍id必须为数字值'))
      }else {
        callback()
      }
    }

    let checkBrotime = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('借阅天数不能为空'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('借阅天数必须为数字值'))
      }else {
        callback()
      }
    }

    return {
      BookborrowList: [],
      page: 1,
      pageSize: 2,
      total: 100,
      page2: 1,
      pageSize2: 2,
      total2: 100,
      BorrowSearch: {},
      BookInfo:{},
      bookList: [],
      dialogFormVisible: false,
      formLabelWidth: '150px',
      Bookbrrowedit: {},
      BBselect:[],
      BIselect:[],
      deleteid:[],
      deletebid:[],
      title: '编辑学生',
      addoredit:0,

      editStuRules: {
        rid: [
          { validator : checkRID, trigger: 'blur'}
        ],
        isbn: [
          { validator : checkISBN, trigger: 'blur'}
        ],
        rname: [
          {required: true, message: '请输入借阅人姓名', trigger: 'blur'},
        ],
        stime: [
          {required: true, message: '请输入借阅的时间', trigger: 'blur'},
        ],
        phone: [
          {required: true, message: '请输入借阅人电话号码', trigger: 'blur'},
        ],
        brotime: [
          {validator : checkBrotime, trigger: 'blur'},
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'},
        ],
      }

    }
  },
  created() {
    this.searchBI()
    this.searchBB()
  },

  methods: {

    jump(){
      this.$router.push('/aboutview');
    },

    saveBookborrow() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.addoredit === 0) {
            const {data: res} = await bookborrrowAPI.add(this.Bookbrrowedit)
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: res.message,
                duration: 1000,
                onClose: () => {
                  this.dialogFormVisible = false
                  this.search()
                  this.findBook()
                }
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message,
              })
            }
          } else {
            const {data: res} = await bookborrrowAPI.update(this.Bookbrrowedit)
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: res.message,
                duration: 1000,
                onClose: () => {
                  this.dialogFormVisible = false
                  this.search()
                  this.findBook()
                }
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message,
                duration: 1000,
              })
            }
          }
        } else {
          console.log('提交失败');
          return false;
        }
      });
    },

    SelectionBookborrow(val) {
      this.BBselect = val;
    },

    SelectionBookInfo(val) {
      this.BIselect = val;
    },


    async findBook() {
      const {data: res} = await bookinfoAPI.findBook()
      if (res.code === 200) {
        this.bookList = res.data.books
      }
    },


    async searchBB() {
      const {data: res} = await bookborrrowAPI.searchBB(this.page, this.pageSize, this.BorrowSearch)
      if (res.code === 200) {
        this.BookborrowList = res.data.res.rows
        this.total = res.data.res.total
      }
    },

    async searchBI() {
      const {data: res} = await bookinfoAPI.searchBI(this.page2, this.pageSize2, this.BookInfo)
      if (res.code === 200) {
        this.bookList = res.data.res.rows
        this.total2 = res.data.res.total
      }
    },

    async search() {
      const {data: res} = await bookborrrowAPI.searchBB(1, this.pageSize, this.BorrowSearch)
      if (res.code === 200) {
        this.BookborrowList = res.data.res.rows
        this.total = res.data.res.total
        this.page = 1
      }
    },

    async search2() {
      const {data: res} = await bookinfoAPI.searchBI(1, this.pageSize2, this.BookInfo)
      if (res.code === 200) {
        this.bookList = res.data.res.rows
        this.total2 = res.data.res.total
        this.page2 = 1
      }
    },

    addBookborrow() {
      this.dialogFormVisible = true
      this.Bookbrrowedit = {}
      this.addoredit = 0
      this.title = "添加借阅记录"
    },

    editBookborrow(row) {
      this.dialogFormVisible = true
      this.addoredit = 1
      this.Bookbrrowedit = row
      this.title = "编辑借阅信息"
    },


    DeleteBookborrow(index,row) {
      this.deleteid = []
      if (row) {
        this.deleteid.push(row.id)
      } else {
        this.deleteid = this.BBselect.map(m => m.id)
      }
      if(this.deleteid.length > 0 ) {
        this.$confirm(`是否真的要删除编号为${this.deleteid}的借阅记录吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let this2 = this
          bookborrrowAPI.delete(this.deleteid)
              .then(({data: res}) => {
                if (res.code === 200) {
                  this.$message({
                    type: 'success',
                    message: res.message,
                    duration: 1000,
                    onClose: () => {
                      this2.search()
                      this2.findBook()
                    }
                  })
                } else {
                  this.$message({
                    type: 'error',
                    message: res.message
                  })
                }
              })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
            duration: 1000,
          });
        });
      }else{
        this.$message({
          type: 'info',
          message: '请至少选择一个要删除的记录',
          duration: 2000,
        })
      }
    },

    DeleteBookInfo(index,row) {
      this.deletebid = []
      if (row) {
        this.deletebid.push(row.isbn)
      } else {
        this.deletebid = this.BIselect.map(m => m.isbn)
      }
      if(this.deletebid.length > 0 ) {
        this.$confirm(`是否真的要删除编号为${this.deletebid}的书籍吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let this2 = this
          bookinfoAPI.deleteBI(this.deletebid)
              .then(({data: res}) => {
                if (res.code === 200) {
                  this.$message({
                    type: 'success',
                    message: res.message,
                    duration: 1000,
                    onClose: () => {
                      this2.search()
                      this2.searchBI()
                    }
                  })
                } else {
                  this.$message({
                    type: 'error',
                    message: res.message
                  })
                }
              })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
            duration: 1000,
          });
        });
      }else{
        this.$message({
          type: 'info',
          message: '请至少选择一个要删除的书籍',
          duration: 2000,
        })
      }
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.searchBB()
    },

    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.searchBB()
    },

    handleSizeChange2(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize2 = val;
      this.searchBI()
    },

    handleCurrentChange2(val) {
      console.log(`当前页: ${val}`);
      this.page2 = val;
      this.searchBI()
    }

  }
}
</script>

<style>
.el-card{
  width: 90%;
  margin: 0 auto;
  margin-bottom: 100px;
}
.el-pagination{
  text-align: right;
  margin-top: 15px;
}
</style>
